package com.wanggsx.library.util.fun.time;

/**
 * Created by wanggsx on 15/10/16.
 */

import android.os.Looper;
import android.util.Log;

import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by fengxiao on 15/10/10.
 */
public class TimeOnLine implements Runnable {
    private TimeCallBack mTimeCallBack;

    public void getBeijingTime(TimeCallBack timeCallBack) {
        mTimeCallBack = timeCallBack;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            Looper.prepare();
            URL url = new URL("http://www.baidu.com");//取得资源对象
            URLConnection uc = url.openConnection();//生成连接对象
            uc.connect(); //发出连接
            long ld = uc.getDate(); //取得网站日期时间
            Date date = new Date(ld); //转换为标准时间对象
            Log.d("timeonline", "wanggsx timeonline : " + new SimpleDateFormat("yyyyMMdd HH:mm:ss").format(date));
            if (mTimeCallBack != null) {
                mTimeCallBack.onFinish(true, date);
                mTimeCallBack = null;
            }
            Looper.loop();
        } catch (Exception e) {
            e.printStackTrace();
            if (mTimeCallBack != null) {
                mTimeCallBack.onFinish(false, null);
            }
        }
    }

}
